#!/bin/bash
#autoSetup tool 

# arg1 deviceURI
# arg2 ppd path

function db ()
{
  >&2 echo "DEBUG: commandtodnp: $@"
}

dnp_renameQueue ()
{
  local -i try=$2
# rename "Dai Nippon Printing" to "DNP"
#db "looking for old-style queue names ..."
qs=($(lpstat -v |awk -v uri="${1}" '{if($NF == uri){sub(":","",$3);print $3}}'))
for q in "${qs[@]}";do
  D=$(lpstat -l -p ${q}|awk '/Description: / {sub("[\t ]*Description:[\t ]*","",$0);print $0}')
  newD="${D/Dai Nippon Printing/DNP}"
  ((try=0))
  if test "${D}" != "${newD}"; then
    db "found a q in ${q} ... updating $D to $newD"
    lpadmin -p ${q} -D "${newD}"
    echo -e '#CUPS-COMMAND\nAutoConfigure\nReportLevels'|lp -d ${q} -- - >/dev/null
  fi
done
if ((try));then
  db "autoSetup $1 will try $((try--)) more times"
  $(sleep $((5-try));dnp_renameQueue "${1}" ${try})&
fi
}

PPD="${2}"

$(sleep 1;dnp_renameQueue "${1}" 5)&

test -r "${PPD}" || exit 1
cat "${PPD}"
exit
